package com.bluesmart.mia;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.loopj.android.http.RequestParams;
import com.sys.Constants;
import com.sys.DemoApp;
import com.umeng.message.UmengRegistrar;
import com.util.Constant;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;
import com.widget.CircleImageView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainNoticeActivity extends BaseActivity implements OnClickListener {
    JSONObject mKown;
    static public String mTime;
    
    public String mTimeLast;
    public String mTimeNext;
    
    int mMainImg = 0;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main_notice);

        findViewById(R.id.left).setOnClickListener(this);
        findViewById(R.id.icon).setOnClickListener(this);
        findViewById(R.id.right).setOnClickListener(this);
        findViewById(R.id.adv).setOnClickListener(this);
        
        initRightMenu();
        login();
        ((TextView)findViewById(R.id.center)).setText(getString(R.string.dashboard));
        
        mMainImg = R.drawable.main_cn;
        if(!isZh()) mMainImg = R.drawable.main_en;
        ((ImageView)findViewById(R.id.adv)).setImageResource(mMainImg);
        
        String url = PreferencesUtils.getString(MainNoticeActivity.this, "home_img");
        if(url != null)
        {
			ImageLoaderHelper.displayImage(mMainImg, (ImageView)findViewById(R.id.adv), url);
        }
        
        int type = MainTabActivity.mMainTabActivity.getType();
        if(type > 0)
        {
        	tackleNotify(10000 + type);
        }
	}
	
	private boolean isZh() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }
	
	@Override
	protected void onDestroy() {
		((DemoApp) getApplicationContext()).removeActivity(this);
		super.onDestroy();
	}
	
	void tackleNotify(int index)
	{
		switch(index)
		{
		case 10001:
			mTime = mTimeNext;
			MainTabActivity.mMainTabActivity.setCurrentTab(1);
			break;
			
		case 10013:
			mTime = mTimeLast;
			MainTabActivity.mMainTabActivity.setCurrentTab(1);
			break;
			
		case 10011:
			startActivity(new Intent(MainNoticeActivity.this,ReportActivity.class));
			break;
			
		case 10015:
		{
			Intent intent = new Intent(MainNoticeActivity.this,NoteDetailActivity.class);
			intent.putExtra("text", JSON.toJSONString(mKown));
			startActivity(intent);
			break;
		}
		
		case 10014:
			MainTabActivity.mMainTabActivity.setCurrentTab(2);
			break;
			
		case 10009:
		{
			Intent in = new Intent(MainNoticeActivity.this,LowBareActivity.class);
			in.putExtra("flag", 0);
			startActivity(in);
			break;
		}
		
		case 10003:
		{
			Intent in = new Intent(MainNoticeActivity.this,LowBareActivity.class);
			in.putExtra("flag", 1);
			startActivity(in);
			break;
		}
		
		case 10016:
			startActivity(new Intent(MainNoticeActivity.this,NotificationActivity.class));
			break;
		}
	}
	
	public void sendAdvRequest(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				
				PreferencesUtils.putString(MainNoticeActivity.this, "home_img", ruser.getString("bimg"));
				ImageLoaderHelper.displayImage(mMainImg, (ImageView)findViewById(R.id.adv), ruser.getString("bimg"));

				JSONArray array = ruser.getJSONArray("notify");
				LinearLayout layout = (LinearLayout)findViewById(R.id.note_layout);
				layout.removeAllViews();
				
				OnClickListener listener = new OnClickListener(){
					@Override
					public void onClick(View arg0) {
						tackleNotify(arg0.getId());
					}
				};
				
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				int count = array.size();
				for(int i = 0; i < count; i++)
				{
					JSONObject obj = array.getJSONObject(i);
					int type = obj.getInteger("notifyType");
					
					if(type == 9)
					{
						if(obj.getInteger("sysytemType") == 1)
						{
							View convertView = mInflater.inflate(R.layout.note_0, null);
							convertView.setId(10000 + type);
							convertView.setOnClickListener(listener);
							layout.addView(convertView);
						}
						else
						{
							View convertView = mInflater.inflate(R.layout.note_6, null);
							convertView.setId(10003);
							((TextView)convertView.findViewById(R.id.date)).setText(Utils.getFormatDate(obj.getString("notifyDate"), MainNoticeActivity.this));
							((TextView)convertView.findViewById(R.id.time)).setText(obj.getString("notifyTime"));
							convertView.setOnClickListener(listener);
							layout.addView(convertView);
						}
					}
					else if(type == 1)
					{
						View convertView = mInflater.inflate(R.layout.note_1, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);

						mTimeNext = obj.getString("startTime");
						
						((TextView)convertView.findViewById(R.id.text0)).setText(getString(R.string.next_up) 
								+ obj.getString("startTime") + getString(R.string.next_up_0));
						((TextView)convertView.findViewById(R.id.text2)).setText(obj.getString("spoon"));
						
						int temp = obj.getIntValue("drinkTemp");
						if(((DemoApp) getApplicationContext()).glbUnit == 1) 
						{
							temp = (int)(1.8*temp) + 32;
							((TextView)convertView.findViewById(R.id.text3)).setText(temp + "°F");
							((TextView)convertView.findViewById(R.id.unit)).setText("oz");
							
							double feedVol = obj.getDoubleValue("feedVol");
							feedVol = 0.0325*feedVol;
							((TextView)convertView.findViewById(R.id.text1)).setText(String.format("%.2f", feedVol ));
						}
						else 
						{
							((TextView)convertView.findViewById(R.id.text3)).setText(temp + "°C");
							((TextView)convertView.findViewById(R.id.text1)).setText(obj.getString("feedVol"));
						}
					}
					else if(type == 13)
					{
						View convertView = mInflater.inflate(R.layout.note_2, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);

						mTimeLast = obj.getString("lastStartTime");
						
						((TextView)convertView.findViewById(R.id.text4)).setText(obj.getString("lastFeedVol"));
						((TextView)convertView.findViewById(R.id.text6)).setText(obj.getString("lastDate"));
						((TextView)convertView.findViewById(R.id.text7)).setText(obj.getString("lastStartTime"));
						
						double lastFeedVol = obj.getDoubleValue("lastFeedVol");
						double totalFeedVol = obj.getDoubleValue("totalFeedVol");
						int temp = obj.getIntValue("lastBrewTemp");
						if(((DemoApp) getApplicationContext()).glbUnit == 1) 
						{
							temp = (int)(1.8*temp) + 32;
							((TextView)convertView.findViewById(R.id.text5)).setText(temp + "°F");
							
							lastFeedVol = 0.0352*lastFeedVol;
							totalFeedVol = 0.0352*totalFeedVol;
							
							((TextView)convertView.findViewById(R.id.text8)).setText(String.format("%.1f", lastFeedVol) + "oz");
							((TextView)convertView.findViewById(R.id.text9)).setText(String.format("%.1f", totalFeedVol) + "oz");
						}
						else 
						{
							((TextView)convertView.findViewById(R.id.text5)).setText(temp + "°C");
							((TextView)convertView.findViewById(R.id.text8)).setText(obj.getString("lastFeedVol") + "ml");
							((TextView)convertView.findViewById(R.id.text9)).setText(obj.getString("totalFeedVol") + "ml");
						}
					}
					else if(type == 12)
					{
						View convertView = mInflater.inflate(R.layout.note_3, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);

						((TextView)convertView.findViewById(R.id.text10)).setText(obj.getString("msTitle"));
						((TextView)convertView.findViewById(R.id.text11)).setText(obj.getString("msId"));
						((TextView)convertView.findViewById(R.id.text12)).setText(obj.getString("msDate"));
						((TextView)convertView.findViewById(R.id.text13)).setText(obj.getString("msTime"));
					}
					else if(type == 3)
					{
						View convertView = mInflater.inflate(R.layout.note_4, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);
					}
					else if(type == 14)
					{
						int noteType = obj.getIntValue("noteType");
						if(noteType == 3)
						{
							View convertView = mInflater.inflate(R.layout.note_7, null);
							convertView.setId(10000 + type);
							convertView.setOnClickListener(listener);
							layout.addView(convertView);
							
							double weight = obj.getDoubleValue("babyweight");
							double height = obj.getDoubleValue("babyheight");
							if(((DemoApp) getApplicationContext()).glbUnit == 1)
							{
								weight = 2.2*weight;
								height = height*0.39;
								
								((TextView)convertView.findViewById(R.id.text8)).setText(String.format("%.1f", weight) + "lb");
								((TextView)convertView.findViewById(R.id.text9)).setText(String.format("%.1f", height) + "inch");
							}
							else
							{
								((TextView)convertView.findViewById(R.id.text8)).setText(String.format("%.1f", weight) + "kg");
								((TextView)convertView.findViewById(R.id.text9)).setText(String.format("%.1f", height) + "cm");
							}
							
							((TextView)convertView.findViewById(R.id.date)).setText(Utils.getFormatDate(obj.getString("noteDate"), MainNoticeActivity.this));
							((TextView)convertView.findViewById(R.id.time)).setText(obj.getString("noteTime"));
							continue;
						}
						else if(noteType == 4)
						{
							View convertView = mInflater.inflate(R.layout.note_8, null);
							convertView.setId(10000 + type);
							convertView.setOnClickListener(listener);
							layout.addView(convertView);
							
							String start = "";
							String end = "";
							
 							String title = obj.getString("noteTitle");
							int pos = title.indexOf("-");
							if(pos > 0)
							{
								start = title.substring(0, pos);
								start = start.substring(start.length() - 5);
								
								end = title.substring(pos + 1);
								end = end.substring(end.length() - 5);
								
								title = start + "-" + end;
							}
							
							((TextView)convertView.findViewById(R.id.text16)).setText(title);
							((TextView)convertView.findViewById(R.id.text17)).setText(obj.getString("noteDate"));
							((TextView)convertView.findViewById(R.id.text18)).setText(obj.getString("noteTime"));
							
							continue;
						}
						
						View convertView = mInflater.inflate(R.layout.note_5, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);
						
						if(noteType == 6)
						{
							((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a67);
							((TextView)convertView.findViewById(R.id.text15)).setText(obj.getString("noteTitle"));
							((TextView)convertView.findViewById(R.id.text16)).setText(
									obj.getString("noteUser") + getString(R.string.add_by) + getString(R.string.first_crawl));
						}
						else if(noteType == 1 || noteType == 2)
						{
							((TextView)convertView.findViewById(R.id.text15)).setText(obj.getString("noteTitle"));
							if(noteType == 1)
								((TextView)convertView.findViewById(R.id.text16)).setText(
									obj.getString("noteUser") + getString(R.string.add_by) + getString(R.string.note1));
							else
								((TextView)convertView.findViewById(R.id.text16)).setText(
									obj.getString("noteUser") + getString(R.string.add_by) + getString(R.string.note2));
							
						}
						else if(noteType == 5)
						{
							((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a96);
							((TextView)convertView.findViewById(R.id.text16)).setText(obj.getString("noteTitle"));
							((TextView)convertView.findViewById(R.id.text15)).setText(getString(R.string.food));
						}

						((TextView)convertView.findViewById(R.id.text17)).setText(obj.getString("noteDate"));
						((TextView)convertView.findViewById(R.id.text18)).setText(obj.getString("noteTime"));

					}
					else if(type == 16)
					{
						View convertView = mInflater.inflate(R.layout.note_5, null);
						convertView.setId(10000 + type);
						convertView.setBackgroundColor(Color.parseColor("#7fd9eb"));
						convertView.setOnClickListener(listener);
						layout.addView(convertView);
						
						//（careType（2：好友请求 8：设备转接申请 6 好友加入消息））
						int careType = obj.getIntValue("careType");
						if(careType == 2)
						{
							((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a92);
						}
						else if(careType == 6)
						{
							((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a93);
						}
						else if(careType == 8)
						{
							((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a94);
						}

						((TextView)convertView.findViewById(R.id.text15)).setText(obj.getString("userno"));
						((TextView)convertView.findViewById(R.id.text16)).setText(obj.getString("careContent"));
						((TextView)convertView.findViewById(R.id.text17)).setText(obj.getString("caredate"));
					}
					else if(type == 15)
					{
						View convertView = mInflater.inflate(R.layout.note_5, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);
						
						mKown = obj;

						int knowledgeType = obj.getIntValue("knowledgeType");
						if(knowledgeType == 1) ((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a89);
						else if(knowledgeType == 2) ((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a95);
						
						((TextView)convertView.findViewById(R.id.text15)).setText(obj.getString("knowledgeTitle")
								+ "\n" + obj.getString("knowledgeContent"));
//						((TextView)convertView.findViewById(R.id.text15)).setSingleLine(false);
					}
					else if(type == 11)
					{
						View convertView = mInflater.inflate(R.layout.note_5, null);
						convertView.setId(10000 + type);
						convertView.setOnClickListener(listener);
						layout.addView(convertView);

						((ImageView)convertView.findViewById(R.id.icon)).setImageResource(R.drawable.a98);
						convertView.findViewById(R.id.line).setVisibility(View.INVISIBLE);
						((TextView)convertView.findViewById(R.id.text16)).setText(obj.getString("reportSummary"));
						((TextView)convertView.findViewById(R.id.text15)).setText(getString(R.string.week_report));
					}
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
//		params.put("babyid", (((DemoApp)getApplicationContext()).getSeletedBaby()).getString("babyid"));
		

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/homepage.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public void getImg() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				PreferencesUtils.putString(MainNoticeActivity.this, "home_img", ruser.getString("bimg"));
				ImageLoaderHelper.displayImage(mMainImg, (ImageView)findViewById(R.id.adv), ruser.getString("bimg"));
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/homepage.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public void sendGetBabyRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				((DemoApp)getApplicationContext()).mBabyList = JSON.parseArray(response);
				if(((DemoApp)getApplicationContext()).mBabyList != null)
				{
					int count = ((DemoApp)getApplicationContext()).mBabyList.size();
					for(int i = 0; i < count; i++)
					{
						JSONObject item = ((DemoApp)getApplicationContext()).mBabyList.getJSONObject(i);
						if(item.getString("isCurr").equals("true")) ((DemoApp)getApplicationContext()).mSelectedBaby = i;
					}
				}
				setUserImage();
				sendHttpRequest();
				sendAdvRequest(true);
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handType", "get");

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/babyInfoHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	SlidingMenu slidingMenu = null;
	void initRightMenu()
	{
		OnClickListener listener = new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				menuBtn(arg0);
			}
		};
		
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setMode(SlidingMenu.RIGHT);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		slidingMenu.setShadowDrawable(R.drawable.shadow);
		slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setMenu(R.layout.right_menu);
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		slidingMenu.setSecondaryShadowDrawable(R.drawable.shadow);
		slidingMenu.setFadeDegree(0.35f);
		
		slidingMenu.findViewById(R.id.btn4).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn5).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn6).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn7).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn8).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn9).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn10).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn11).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn12).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn13).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn14).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn15).setOnClickListener(listener);
		slidingMenu.findViewById(R.id.btn16).setOnClickListener(listener);
	}
	
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				
				JSONObject json = JSON.parseObject(response);
				if(json.keySet().size() > 0)
				{
					slidingMenu.findViewById(R.id.btn10).setVisibility(View.VISIBLE);
					((TextView)slidingMenu.findViewById(R.id.btn10)).setText(json.getString("deviceName"));
					((TextView)slidingMenu.findViewById(R.id.btn9)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
					slidingMenu.findViewById(R.id.btn9).setOnClickListener(null);
				}
			}
		};
		
		JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();
		if(obj == null) return;
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("babyid", (((DemoApp)getApplicationContext()).getSeletedBaby().getString("babyid")));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/DownLoadDeviceInfo.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	protected void onResume()
	{
		super.onResume();
		setUserImage();
		sendAdvRequest(false);
		setNewMsg();
	}
	
	public void setCenterTitle()
	{
	}
	
	void setUserImage()
	{
		if(((DemoApp)getApplicationContext()).mBabyList != null)
		{
			JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();
			if(obj != null)
			{
				TextView tv = (TextView)slidingMenu.findViewById(R.id.btn10);
				tv.setTag(obj.toString());
				
				Date date = Utils.ConverToDate(obj.getString("bday"), "yyyy-MM-dd");
				int days = (int) ((System.currentTimeMillis() - date.getTime())/(24*3600*1000));
				
		        ((TextView)findViewById(R.id.birthday)).setText(Utils.getFormatDate(obj.getString("bday"),this));
		        
		        if(Utils.isZh(this))
		        {
		        	((TextView)findViewById(R.id.age)).setText(obj.getString("nickname") + "的第"
							+ days + getString(R.string.day_age));
		        }
		        else
		        {
		        	((TextView)findViewById(R.id.age)).setText(obj.getString("nickname") + " "
							+ days + getString(R.string.day_age));
		        }
		        
		        findViewById(R.id.icon).setVisibility(View.VISIBLE);
		        findViewById(R.id.left).setVisibility(View.INVISIBLE);
		        
		        ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon), 
						obj.getString("image"));
			}
		}
	}
	
	void menuBtn(View arg0)
	{
		slidingMenu.toggle(false);
		
		switch(arg0.getId())
		{
		case R.id.btn5:
			startActivity(new Intent(this,NotificationActivity.class));
			break;

		case R.id.btn6:
			startActivity(new Intent(this,GeneralActivity.class));
			break;
			
		case R.id.btn4:
			startActivity(new Intent(this,AccountActivity.class));
			break;
			
		case R.id.btn9:
			startActivity(new Intent(this,AddDeviceActivity.class));
			break;
			
		case R.id.btn10:
		case R.id.btn11:
		case R.id.btn12:
		case R.id.btn13:
		case R.id.btn14:
		case R.id.btn15:
		case R.id.btn16:
		{
			Intent intent = new Intent(this,DeviceInfoActivity.class);
			intent.putExtra("obj", (String)arg0.getTag());
			startActivity(intent);
			break;
		}
		}
	}
	
	@Override
	public void onBackPressed() {
		exitApp();
	}

	private long exitTime = 0;
	public void exitApp() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(this, "再按一次退出", Toast.LENGTH_LONG).show();
			exitTime = System.currentTimeMillis();
		} else {
			this.finish();
		}
	}
	
	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.icon:
			startActivity(new Intent(this,BabyViewActivity.class));
			break;
			
		case R.id.left:
//			findViewById(R.id.command).setVisibility(View.VISIBLE);
			break;
		
		case R.id.right:
			slidingMenu.toggle(true);
			break;
			
		case R.id.left_s:
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
			
		case R.id.baby1:
			startActivity(new Intent(this,BabyProfileActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
			
		case R.id.baby2:
			startActivity(new Intent(this,BabyCaregiversActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;

		case R.id.baby0:
			startActivity(new Intent(this,BabyProfileEditActivity.class));
			findViewById(R.id.command).setVisibility(View.INVISIBLE);
			break;
			
		case R.id.adv:
			showImagePicker();
			break;
	}
	}
	
	void showImagePicker()
	{
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		
		OnClickListener listen = new OnClickListener()
		{
			@Override
			public void onClick(View arg0) {
				if(arg0.getId() == R.id.cancel) mDialog.dismiss();
				else if(arg0.getId() == R.id.pic)
				{
					mDialog.dismiss();
					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType("image/*");
					startActivityForResult(getAlbum, 10);
				}
				else if(R.id.dialog_layout == arg0.getId())
				{
					mDialog.dismiss();
				}
				else
				{
					mDialog.dismiss();
					startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 11);
				}
			}
		};

		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(listen);
		mDialog.findViewById(R.id.pic).setOnClickListener(listen);
		mDialog.findViewById(R.id.cancel).setOnClickListener(listen);
		mDialog.findViewById(R.id.dialog_layout).setOnClickListener(listen);
		mDialog.show();
	}

	private File mPhotoFile;
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		
		if(requestCode != 11 && requestCode != 10)
		{
			((BabyActivity)findViewById(R.id.view0)).onActivityResult(requestCode, resultCode, data);
			super.onActivityResult(requestCode, resultCode, data);
			return;
		}
		
		Bitmap bitmap = null;
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 11) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 10) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			sendHttpImgRequest(bitmap);
		}
	}
	
	private void sendHttpImgRequest(final Bitmap bitmap) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					((ImageView) findViewById(R.id.adv)).setImageBitmap(bitmap);
					ToastUtil.showToastWithAlertPic(R.string.success);
					
					getImg();
				}
				else if (ruser.getString("resCode").equals("2000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_2000);
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("handtype", "homepage");
		try {
			params.put("filename", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constant.SERVER_URL + "/sw/uploadimg.ashx", params, loginHandler);
	}
	
	public void showShedule()
	{
		Animation anim = AnimationUtils.loadAnimation(MainNoticeActivity.this, R.anim.slide_in_from_top);  
        findViewById(R.id.view1).startAnimation(anim);  
        findViewById(R.id.view1).setVisibility(View.VISIBLE);
	}
	
	public void startActivityForBaby(int index)
	{
		switch(index)
		{
		case 0:
			startActivityForResult(new Intent(this,AddProfileWeightActivity.class), 10);
			break;
			
		case 1:
			startActivityForResult(new Intent(this,AddProfileHeightActivity.class), 11);
			break;
			
		case 2:
			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType("image/*");
			startActivityForResult(getAlbum, 3);
			break;
			
		case 3:
			startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 4);
			break;
		}
	}
	
	void setNewMsg()
	{
		if(((DemoApp)getApplicationContext()).isNewMsg)
		{
			((TextView)slidingMenu.findViewById(R.id.btn5)).setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.bg_news, 0, R.drawable.a17, 0);
			((ImageButton)findViewById(R.id.right)).setImageResource(R.drawable.unread);
		}
		else
		{
			((TextView)slidingMenu.findViewById(R.id.btn5)).setCompoundDrawablesWithIntrinsicBounds(
					0, 0, R.drawable.a17, 0);
			((ImageButton)findViewById(R.id.right)).setImageResource(R.drawable.a25);
		}
	}
	
	private void login() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("resCode").equals("1000")) {
					PreferencesUtils.putString(getApplicationContext(), "accessToken", ruser.getString("accessToken"));
					sendGetBabyRequest();
					if(ruser.getString("isunreadmsg").equals("true"))
					{
						((DemoApp)getApplicationContext()).isNewMsg = true;
					}
					else
					{
						((DemoApp)getApplicationContext()).isNewMsg = false;
					}
					
					setNewMsg();
				}
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("userName", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("tid", "");
		params.put("deviceid", UmengRegistrar.getRegistrationId(this));

		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/login.ashx", JSON.toJSONString(params), loginHandler);
	}
}
